﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CentralMonitoring.DataBase;
using Models;

namespace CentralMonitoring
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            LoginIn();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            var temp = Db.Sqllite.Select<TempData>().Where(db => db.Id == 1).ToList();
            if (temp.Count > 0)
            {
                cbRemember.Checked = temp[0].cbRemember;
                cbAutoLogin.Checked = temp[0].cbAutoLogin;
                tbUserName.Text = temp[0].UserName;
                tbPwd.Text = temp[0].Password;
            }

            if (!cbRemember.Checked)
            {
                tbUserName.Text = "";
                tbPwd.Text = "";
                return;
            }

            if (cbAutoLogin.Checked)
            {
                LoginIn();
            }
        }

        private void LoginIn()
        {
            TempSave();
            var user = Db.Sqllite.Select<User>().Where(db => db.UserName == tbUserName.Text && db.Password == tbPwd.Text).ToList();
            if (user.Count < 1)
            {
                return;
            }
            Hide();
            MainForm mainForm = new MainForm();
            mainForm.ShowDialog();
            Show();
        }

        private void TempSave()
        {
            Db.Sqllite.Update<TempData>()
                .Set(db => db.UserName,tbUserName.Text )
                .Set(db => db.Password, tbPwd.Text)
                .Set(db => db.cbRemember, cbRemember.Checked)
                .Set(db => db.cbAutoLogin, cbAutoLogin.Checked)
                .Where(id => id.Id == 1).ExecuteAffrows();
        }

        private void cbRemember_CheckedChanged(object sender, EventArgs e)
        {
            TempSave();
        }

        private void cbAutoLogin_CheckedChanged(object sender, EventArgs e)
        {
            TempSave();
        }
    }
}
